<template>
  <view class="container">
    <!-- 提交表单 -->
    <u-form :model="form" ref="uForm">
      <u-form-item label="身份证姓名" label-width="180" prop="idCardName" required
      >
        <u-input v-model="form.idCardName" disabled placeholder=""
        />
      </u-form-item>
      <u-form-item label="身份证号码" label-width="180" prop="idCardNo" required
      >
        <u-input v-model="form.idCardNo" disabled placeholder=""
        />
      </u-form-item>
      <view @click="showIdCardBeginDatePick = true">
        <u-form-item @click="showIdCardBeginDatePick = true" label="身份证有效起期"
                     label-width="200" prop="idCardBeginDate" required
        >
          <text :style="{color:(form.idCardBeginDate?'#303133': '#C0C4CC')}">{{ getIdCardBeginDate }}</text>
          <u-picker v-model="showIdCardBeginDatePick" mode="time" @confirm="onIdCardBeginDateConfirm"></u-picker>
        </u-form-item>
      </view>
      <view @click="onIdCardEndDateClick" >
        <u-form-item label="身份证有效止期"
                     label-width="200" prop="idCardEndDate"
                     :disabled = 'form.isLongIdCard === 1' required
        >
          <text :style="{color:(form.idCardEndDate?'#303133': '#C0C4CC')}">{{ getIdCardEndDate }}</text>
          <u-picker v-model="showIdCardEndDatePick" mode="time" @confirm="onIdCardEndDateConfirm"></u-picker>
        </u-form-item>
      </view>
      <u-form-item label-width="200" label="是否长期身份证">
        <u-radio-group v-model="form.isLongIdCard">
          <u-radio
            @change="longIdCardChange"
            v-for="(item, index) in longIdCardRadio" :key="index"
            :name="item.id"
          >
            {{item.name}}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="身份证地址" label-width="180" prop="idCardAddress" required>
        <u-input v-model="form.idCardAddress" placeholder="请输入身份证地址"
        />
      </u-form-item>
      <u-form-item label="签发机关" label-width="180" prop="issuingAuthority" required
      >
        <u-input v-model="form.issuingAuthority" placeholder="请输入签发机关"
        />
      </u-form-item>
      <u-form-item label="开户银行卡号" label-position="top" prop="bankCardNo" required>
        <u-input v-model="form.bankCardNo" placeholder="请输入开户银行卡号" @blur="vailCard"
        />
      </u-form-item>
      <u-form-item label="开户银行" label-position="top" prop="bankName" required>
        <u-input
          v-model="form.bankName"
          type="select"
          :select-open="actionNameShow"
          @click="actionNameShow = true"
          placeholder="请选择银行卡开户银行"
        />
        <u-select
          v-model="actionNameShow"
          :list="actionNameList"
          mode="single-column"
          @confirm="actionNameCallback"
        ></u-select>
      </u-form-item>
      <u-form-item label-width="200" label="开户行支行名称" prop="bankBranch" required>
        <u-input
          v-model="form.bankBranch" placeholder="请填写开户行支行名称"/>
      </u-form-item>
      <u-button type="primary" shape="square" :ripple="true" size="default" @click="submit"
                :disabled="disabledBtn"
      >{{ btnText }}
      </u-button
      >

    </u-form>
  </view>
</template>

<script>
import reportApi from '@/api/modules/report'

export default {
  name: "TaxVerify",
  data() {
    return {
      form: {
        idCardName: '',
        idCardNo: '',
        inductionDate: null,
        status: null,
        inductionId: null,
        // 银行卡号
        bankCardNo: null,
        // 开户银行
        bankName: null,
        // 身份证地址
        idCardAddress: null,
        // 签发机关
        issuingAuthority: null,
        bankBranch: "", // 开户行支行
        // 身份证有效起期
        idCardBeginDate: null,
        // 身份证有效止期
        idCardEndDate: null,
        // 是否长期身份证
        isLongIdCard: 0,
      },
      rules: {
        bankName: [
          {
            required: true,
            message: "请选择银行卡开户银行",
            trigger: ["change", "blur"],
          },
        ],
        bankCardNo: [
          {
            required: true,
            message: "请输入开户银行卡号",
            trigger: ["change", "blur"],
          },
        ],
        idCardName: [
          {
            required: true,
            message: "请输入身份证姓名",
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              return !/^[0-9]+.?[0-9]*$/.test(value);
            },
            message: "身份证姓名不正确",
            trigger: ["change", "blur"],
          },
        ],
        idCardNo: [
          {
            required: true,
            message: "请输入身份证号码",
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.idCard(value);
            },
            message: "身份证号码不正确",
            trigger: ["change", "blur"],
          },
        ],
        idCardAddress: [{required: true, message: "请输入身份证地址", trigger: ["change", "blur"],},],
        issuingAuthority: [{required: true, message: "请输入签发机关", trigger: ["change", "blur"]}],
        idCardBeginDate: [{required: true, message: "请选择身份证有效起期", trigger: ["change", "blur"]}],
        idCardEndDate: [{required: true, message: "请选择身份证有效止期", trigger: ["change", "blur"]}],
        bankBranch: [{required: true, message: "请填写开户行支行", trigger: ["change", "blur"]}],
      },
      longIdCardRadio: [{name: '否', id: 0}, {name: '是', id: 1}],
      actionNameList: [],
      actionNameShow: false,
      checkBankName: {},
      qrCodeType: null,
      vaildCard: null,
      // 是否显示身份证有效起期pick
      showIdCardBeginDatePick: false,
      // 是否显示身份证有效止期pick
      showIdCardEndDatePick: false,
      needCert: true,
      disabledBtn: true,
      btnText: '进行税务认证',
    }
  },
  methods: {
    async getBankDictList() {
      try {
        const res = await this.$api.riders.getDictList({type: 'rid_bank_name'})
        if (res && res.code !== 200) {
          uni.showToast({
            title: res.msg,
            icon: "error",
          });
          return
        }
        if (res.data && res.data.length > 0) {
          res.data.forEach(item => {
            this.actionNameList.push({
              value: item.dictValue,
              label: item.dictLabel,
            });
          })
        }
      } catch (e) {
        uni.showToast({
          title: '查询银行下拉列表错误',
          icon: "error",
        });
      }
    },
    async getInduction() {
      try {
        this.form = {
          idCardName: '',
          idCardNo: '',
          inductionDate: null,
          status: null,
          inductionId: null,
          bankCardNo: null,
          bankName: null,
          idCardAddress: null,
          issuingAuthority: null,
          bankBranch: "",
          idCardBeginDate: null,
          idCardEndDate: null,
          isLongIdCard: 0,
        }
        const {data, msg} = await this.$api.riders.getInduction()
        if (!data) {
          if (msg === '不存在微信用户记录') {
            // 跳转到简单登录页注册微信记录
            this.$store.commit("UPDATE_ROUTEURL", "/pages/simple_login/index");
            return
          }
          this.btnText = '未有过入职记录,无法税务认证'
          this.disabledBtn = true
          uni.showToast({
            title: '未有过入职记录,无法税务认证',
            icon: "error",
          });
          return
        }
        this.form = {...data}
        if (this.form.idCardEndDate === '2099-12-31') {
          this.form.isLongIdCard = 1
        } else {
          this.form.isLongIdCard = 0
        }
        if (this.actionNameList && this.actionNameList.length > 0) {
          this.actionNameList.forEach((item) => {
            if (this.form.bankName === item.value) {
              this.form.bankName = item.label;
              this.checkBankName = {
                value: item.value,
                label: item.label,
              };
            }
          });
        }
        let invalidStatus = data && data.status ? (data.status !== '40' && data.status !== '50') : false
        let invalidOtherStatus = data && data.otherStatus ? (data.otherStatus !== '80' && data.otherStatus !== '90') : false
        if (invalidStatus || (!invalidStatus && invalidOtherStatus)) {
          this.btnText = '未走完入职流程,无法税务认证'
          this.disabledBtn = true
          uni.showToast({
            title: '未走完入职流程,无法税务认证',
            icon: "error",
          });
          return
        }
        this.btnText = '税务认证'
        this.disabledBtn = false
      } catch (e) {
        uni.showToast({
          title: '查询入职状态错误' + e,
          icon: "error",
        });
        this.btnText = '查询入职状态错误' + e
        this.disabledBtn = true
        let text = '税务认证查询入职记录错误 ' + ' \n '
        text += ` ex: ${e}  \n `
        text += ` stack: ${e.stack} \n`
        await reportApi.errorReport({error: text, appId: '', openId: '',});
      }
    },
    async submit() {
      if (this.disabledBtn === true) {
        return
      }
      await this.vailCard()
      this.$refs.uForm.validate(async valid => {
        if (valid && this.vaildCard) {
          await this.refreshTaxInfo()
        } else {
          uni.showModal({
            title: "提示",
            content: "验证失败",
          });
        }
      });
    },
    // 刷新税务信息
    async refreshTaxInfo() {
      try {
        const submitForm = {...this.form}
        submitForm.bankName = this.checkBankName.value || ""
        const res = await this.$api.riders.refreshTaxInfo(submitForm)
        if (res && res.code !== 200) {
          uni.showToast({
            title: res.msg,
            icon: 'error'
          })
          return
        }
        // 跳转到税务认证
        await this.getTaxDept()
      } catch (e) {
        uni.showToast({
          title: '刷新税务信息错误' + e,
          icon: 'error'
        })
      }
    },
    // 同步税务认证信息
    async syncTaxCert() {
      await this.$api.tax.syncCert()
    },
    // 查询是否需要税务认证
    async getNeedCert() {
      const res = await this.$api.tax.getNeedCert()
      this.needCert = res && res.code === 200 && res.data.need === true
      if (this.needCert === false) {
        this.btnText = '已通过税务认证,无需重复认证'
        this.disabledBtn = true
      }
    },
    // 跳转税务认证
    async getTaxDept() {
      try {
        const res = await this.$api.tax.getTaxDept()
        if (res && res.code === 200) {
          if (res.data) {
            // 跳转到税务认证
            let h5Res = await this.$api.tax.getH5Url();
            if (h5Res && h5Res.code === 200) {
              window.open(h5Res.msg, '_self')
            }
          } else {
            uni.showToast({
              icon: "error",
              title: "部门税务认证已关闭",
            });
          }
        } else if (res) {
          uni.showToast({
            icon: "error",
            title: res.msg,
          });
        }
      } catch (e) {
        uni.showToast({
          icon: "error",
          title: `跳转税务认证错误${e}`,
        });
      }
    },
    // 处理身份证有效起期变更事件
    onIdCardBeginDateConfirm(result){
      this.form.idCardBeginDate = `${result.year}-${result.month}-${result.day}`
    },
    // 处理身份证有效止期变更事件
    onIdCardEndDateConfirm(result) {
      this.form.idCardEndDate = `${result.year}-${result.month}-${result.day}`
    },
    // 是否长期身份证变更
    longIdCardChange(e) {
      this.form.idCardEndDate = e === 1 ? '2099-12-31': null
    },
    // 身份证有效止期点击
    onIdCardEndDateClick() {
      if (this.form.isLongIdCard === 1) {
        return
      }
      this.showIdCardEndDatePick = true
    },
    actionNameCallback(e) {
      this.form.bankName = e[0].label;
      this.checkBankName = e[0];
    },
    vailCard() {
      return this.$u
        .get("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json", {
          cardNo: this.form.bankCardNo,
          cardBinCheck: true,
        })
        .then((res) => {
          if (!res.validated) {
            uni.showToast({
              icon: "none",
              title: "请输入正确的银行卡号",
            });
            this.vaildCard = false
          } else {
            this.vaildCard = true;
          }
        });
    },
  },
  computed: {
    // 计算身份证有效起期
    getIdCardBeginDate() {
      if (!this.form.idCardBeginDate) {
        return '请选择身份证有效起期'
      }
      return this.form.idCardBeginDate
    },
    // 计算身份证有效止期
    getIdCardEndDate() {
      if (!this.form.idCardEndDate) {
        return '请选择身份证有效止期'
      }
      return this.form.idCardEndDate
    }
  },
  async onShow() {
    await this.getBankDictList()
    await this.getInduction()
    if (this.form.inductionId) {
      try {
        // 同步税务认证信息
        await this.syncTaxCert()
      } catch (e) {
        uni.showToast({
          icon: "error",
          title: `同步税务认证信息错误${e}`,
        });
      }
      try {
        // 查询是否需要税务认证
        await this.getNeedCert()
      } catch (e) {
        uni.showToast({
          icon: "error",
          title: `查询税务认证状态错误${e}`,
        });
      }
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
}
</script>

<style scoped lang="scss">
.container {
  box-sizing: border-box;
  padding: 20px;
}
</style>
